package com.flaskpy.web.eternity.auth.jwt.service.impl;

import com.flaskpy.web.eternity.auth.jwt.entiry.AccessParam;
import com.flaskpy.web.eternity.auth.jwt.entiry.JwtPayLoad;
import com.flaskpy.web.eternity.auth.jwt.service.IAccessDecisionService;
import com.flaskpy.web.eternity.auth.jwt.context.JwtContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

public class RbacVoter implements AccessDecisionVoter<Object> {
    @Autowired
    private IAccessDecisionService accessDecisionService;
    AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }

    @Override
    public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
        if (authentication == null) {
            return ACCESS_DENIED;
        }
        int result = ACCESS_ABSTAIN;
        FilterInvocation filterInvocation=(FilterInvocation)object;
        HttpServletRequest request = filterInvocation.getHttpRequest();
        Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);
        JwtPayLoad jwtPyload = JwtContextHolder.currentJwtPayload();
        for (ConfigAttribute attribute : attributes) {
            if (this.supports(attribute)) {
                result = ACCESS_DENIED;
                AccessParam accessParam=new AccessParam(){{
                    setAttributes(attributes);
                    setAuthentication(authentication);
                    setFilterInvocation(filterInvocation);
                    setJwtPayLoad(jwtPyload);
                    setRequest(request);
                }};
                if(this.accessDecisionService.access(accessParam)){
                    return ACCESS_GRANTED;
                }
            }
        }
        return result;
    }
    Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
        return authentication.getAuthorities();
    }

}
